package com.fingard.dsp.bank.directbank.czb01;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ICurrencyExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.ReqExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.ReqQryExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.RetAtsExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.detail.RetAtsExchangeDetail;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import static com.fingard.text.StringHelper.trimEndFileSp;

/**
 * Created by xtt
 */
public class CZB01SettlementExchange extends CZB01Base implements ICurrencyExchange {
    @Override
    public RetAtsExchange exchangePay(ReqExchange exchangePay) throws Exception {
        //返回ATS的对象
        RetAtsExchange retAts = new RetAtsExchange(exchangePay.reqHeader);
        RetAtsExchangeDetail retDetail = new RetAtsExchangeDetail();
        try {
            CZB01Header bankHeader = new CZB01Header();
            bankHeader.transCode = "510006";//交易代码
            bankHeader.reqSeqNo = exchangePay.reqHeader.transSeqID;
            //发银行报文的XML对象
            XmlTextWriter xmlWriter = new XmlTextWriter();
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("set_accno", exchangePay.singleDetail.payAct);
            xmlWriter.writeElementString("cur_code", exchangePay.singleDetail.payCur);
            xmlWriter.writeElementString("set_amt", exchangePay.singleDetail.payAmount);
            xmlWriter.writeElementString("rmb_accno", exchangePay.singleDetail.recAct);

            String cap_srctype = getBankConfig().getMapValueByKey("codeTypeMapping", exchangePay.singleDetail.transCode);
            String cap_src = getBankConfig().getMapValueByKey("codeTypeMapping", cap_srctype);
            xmlWriter.writeElementString("cap_src", cap_src);//结汇资金来源
            xmlWriter.writeElementString("cap_srctype", cap_srctype);//结汇资金来源类别
            xmlWriter.writeElementString("cap_srcdetail", exchangePay.singleDetail.transCode);//结汇资金详细来源

            xmlWriter.writeElementString("trans_type", this.getBankConfig().getValueAsString("settlementTransType"));
            xmlWriter.writeElementString("profit_account", exchangePay.singleDetail.recAct);
            xmlWriter.writeEndElement();//body
            xmlWriter.writeEndElement();//ap
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                    if ("0000".equals(tmpRetCode)) {
                        retDetail.respCode = "0";
                        retDetail.transState = tmpRetCode;
                        retDetail.payInfoCode = tmpRetInfo;
                        retDetail.respInfo = tmpRetInfo;
                        retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.transState = tmpRetCode;
                        retDetail.respInfo = tmpRetInfo;
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = tmpStrRet[0];
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
            if (retDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(retDetail.reqSeqID)) {
                retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    /***
     * 银行支持批量 目前ATS采用单笔查询
     * @param exchangeQry
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsExchange qryExchangePay(ReqQryExchange exchangeQry) throws Exception {
        //返回ATS的对象
        RetAtsExchange retAts = new RetAtsExchange(exchangeQry.reqHeader);
        RetAtsExchangeDetail detail = new RetAtsExchangeDetail();
        String downloadFilePath = trimEndFileSp(bankFront.bkTransFolder) + File.separator;//共享目录路径
        try {
            CZB01Header bankHeader = new CZB01Header();
            bankHeader.transCode = "510007";//交易代码
            bankHeader.reqSeqNo = exchangeQry.reqHeader.transSeqID;
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("set_accno", exchangeQry.payAct);
            xmlWriter.writeElementString("start_date", exchangeQry.bgnDate);
            xmlWriter.writeElementString("end_date", exchangeQry.endData);
            xmlWriter.writeElementString("req_no", exchangeQry.reqHeader.transSeqID);

            xmlWriter.writeElementString("status", "");
            xmlWriter.writeEndElement();//body
            xmlWriter.writeEndElement();//ap
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                    if ("0000".equals(tmpRetCode)) {
                        //获取明细文件
                        int recordNum = Integer.valueOf(tmpBkReader.getFirstText("/ap/body/record_num"));
                        int fieldNum = Integer.valueOf(tmpBkReader.getFirstText("/ap/body/field_num"));
                        if (recordNum > 0) {
                            //结汇账号|结汇账号户名|币种|结汇金额|结汇人民币账号|结汇资金来源|结汇资金来源类别|结汇资金详细来源|交易主体类别|结汇汇率|结汇人民币金额|结汇时间|请求号|受理状态|申请日期|受理日期|流水号|
                            String fileName = tmpBkReader.getFirstText("/ap/body/file_name");
                            String p_FileFullPath = getTempFileDirectory() + File.separator + Format.Time6Format.format(new Date());//下载到的本地路径
                            WriteBankLogLn("共享目录文件，位于：" + downloadFilePath);
                            String repData = "";
                            StringBuilder p_sb = new StringBuilder();
                            if (SmbFileUtil.smbDownloadInChar(p_FileFullPath, downloadFilePath, fileName, p_sb) == 1) {
                                WriteBankLogLn("文件下载成功，位于：" + p_FileFullPath);
                                p_FileFullPath = p_FileFullPath + File.separator + fileName;
                                repData = FileHelper.readFileText(p_FileFullPath, getCharset());
                            } else {
                                detail.respCode = "-1";
                                detail.respInfo = p_sb.toString();
                                retAts.writeRetDetail(detail);
                                return retAts;
                            }
                            StringBuilder tmpSbLog = new StringBuilder();
                            ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(repData, "|", fieldNum, recordNum + 1, tmpSbLog);
                            if (tmpSbLog.length() == 0) {
                                for (int i = 1; i < tmpArrayList.size(); i++) {
                                    detail.respCode = "0";
                                    detail.transState = tmpArrayList.get(i)[13];
                                    detail.payInfoCode = detail.transState;
                                    detail.respInfo = tmpArrayList.get(i)[13];
                                    detail.settlementRate=tmpArrayList.get(i)[9];
                                    detail.settlementRmbAmount=tmpArrayList.get(i)[10];
                                }
                            } else {
                                detail.respCode = "-1";
                                detail.respInfo = tmpSbLog.toString();
                            }
                        } else {
                            detail.respCode = "0";
                            detail.respInfo = "交易记录为空";
                        }
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = tmpRetInfo;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else {
                detail.respCode = "-1";
                detail.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            detail = new RetAtsExchangeDetail();
            detail.respCode = "-1";
            detail.respInfo = ex.getMessage();
            ex.printStackTrace();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }
}

